//
//  CommentViewController.m
//  CarFace
//
//  Created by dlios on 15-3-24.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "CommentViewController.h"
#import "SelectViewController.h"
#import "FinderViewController.h"
#import "UIButton+InitButton.h"
#import "ComSaveViewController.h"
#import "ComTableViewCell.h"
#import "Forum.h"


@interface CommentViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UISegmentedControl *segmentControl;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, retain)NSString *str;
@property(nonatomic, retain)NSString *strCom;
@property(nonatomic, retain)UIButton *saveButton;
@property(nonatomic, retain)UILabel *saveLable;
@property(nonatomic, retain)UILabel *titleLable;
@property(nonatomic, retain)NSNumber *rowcountStr;
@property(nonatomic, retain)UILabel *rowcountL;
@property(nonatomic, assign)NSInteger num;
@property(nonatomic, retain)NSNumber *pageIndex;

@end

@implementation CommentViewController

- (void)dealloc
{
    [_segmentControl release];
    [_tableView release];
    [_str release];
    [_arr release];
    [_rowcountStr release];
    [_rowcountL release];
    [_strCom release];
    [_saveLable release];
    [_titleLable release];
    [_pageIndex release];
    [super dealloc];


}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.num = 0;
    self.arr = [NSMutableArray array];
    NSString *str = @"http://app.api.autohome.com.cn/autov4.6/club/topics-a2-pm2-v4.6.1-b200009-bto-r0-ss0-o0-p1-s50-qf0.html";
    NSString *ipS = self.foru.bbsid;
    self.str = [str stringByReplacingOccurrencesOfString:@"200009" withString:ipS];
  
    [self handerData];
    
    
//  ************* 布局: *****************
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    
    UIButton *returnButton = [UIButton buttonWithTitle:@"返回" frame:CGRectMake(0, 20, width / 4, 30) target:self action:@selector(clickReturnButton:)];
    [returnButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [returnButton setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [self.view addSubview:returnButton];
    
    UIButton *finderButton = [UIButton buttonWithTitle:nil frame:CGRectMake(width - 50, 20, 30, 30) target:self action:@selector(clickFinderButton:)];
    [finderButton setImage:[UIImage imageNamed:@"sousuo.png"] forState:UIControlStateNormal];
    [self.view addSubview:finderButton];
    
    self.titleLable = [[UILabel alloc]initWithFrame:CGRectMake(width / 2 - 50, 30, 100, 30)];
    self.titleLable.text = self.foru.bbsname;
    self.titleLable.textAlignment = NSTextAlignmentCenter;
    [self.titleLable sizeToFit];
    [self.view addSubview:self.titleLable];
    [_titleLable release];
    
   
  
    self.segmentControl = [[UISegmentedControl alloc]initWithItems:@[@"最后回复", @"最新发布", @"精华帖"]];
    self.segmentControl.frame = CGRectMake(50, 65, width - 100 , 30);
    [self.segmentControl addTarget:self action:@selector(clickSegmentcontrol:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentControl];
    [_segmentControl release];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 110, width - 10, height - 110 - 49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView addHeaderWithTarget:self action:@selector(addHeader:)];
    [self.tableView addFooterWithTarget:self action:@selector(addFooter:)];
    [self.tableView setHeaderRefreshingText:@"下拉刷新"];
    [self.tableView setFooterRefreshingText:@"网络加载中..."];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.rowcountL = [[UILabel alloc]initWithFrame:CGRectMake(width / 2 - 40 ,height - 40, width / 6 + 30, 40)];
    self.rowcountL.text = [NSString stringWithFormat:@"共%@帖", self.rowcountStr];
    self.rowcountL.textAlignment = NSTextAlignmentCenter;
    self.rowcountL.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:self.rowcountL];
    [_rowcountL release];
    
    
    
    self.saveButton = [UIButton buttonWithTitle:nil frame:CGRectMake(width * 2 / 3, height - 40, width / 6, 20) target:self action:@selector(clickSaveButton:)];
    [self.saveButton setImage:[UIImage imageNamed:@"iconfont-iconfontshoucang.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.saveButton];
    
    self.saveLable = [[UILabel alloc]initWithFrame:CGRectMake(width * 2 / 3, height - 15, width / 6, 10)];
    self.saveLable.text = @"收藏";
    self.saveLable.textAlignment = NSTextAlignmentCenter;
    self.saveLable.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:self.saveLable];
    [_saveLable release];
    
    UIButton *favoriteButton = [UIButton buttonWithTitle:nil frame:CGRectMake(width * 2 / 3 + width / 6, height - 40, width / 6, 20) target:self action:@selector(clickFaviriteButtonAction:)];
    [favoriteButton setImage:[UIImage imageNamed:@"iconfont-shoucang.png"] forState:UIControlStateNormal];
    [self.view addSubview:favoriteButton];
    
    UILabel *favoriteLable = [[UILabel alloc]initWithFrame:CGRectMake(width * 2 / 3 + width / 6, height - 15, width / 6, 10)];
    favoriteLable.text = @"收藏夹";
    favoriteLable.textAlignment = NSTextAlignmentCenter;
    favoriteLable.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:favoriteLable];
    [favoriteLable release];
}

#pragma mark - 保存的方法
- (void)clickSaveButton:(UIButton *)button
{
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    
    self.db = [DataHander shareInstance];
    [self.db openDB];
    if (self.flag == YES) {
        [self.saveButton setImage:[UIImage imageNamed:@"iconfont-iconfontshoucang.png"] forState:UIControlStateNormal];
        self.saveLable.text = @"收藏";
        self.saveLable.frame = CGRectMake(width * 2 / 3, height - 15, width / 6, 10);
        self.saveLable.textColor = [UIColor blackColor];
        // 删除数据
        [self.db deleteData:self.foru.bbsid];
        
//        NSLog(@"%@", [self.db selectAll]);
        
    }else{
        [self.saveButton setImage:[UIImage imageNamed:@"iconfont-collect.png"] forState:UIControlStateNormal];
        self.saveLable.text = @"已收藏";
        self.saveLable.textColor = [UIColor grayColor];
        self.saveLable.frame = CGRectMake(width * 2 / 3 - 2, height - 15, width / 6 + 3, 10);
    
        // 创建表
        [self.db createTable];
        // 插入数据
        Listing *movie = [[Listing alloc]init];
        movie.bbsname = self.foru.bbsname;
        movie.bbsid = self.foru.bbsid;
        [self.db insertForumSave:movie];
        // 显示所有数据
//        NSLog(@"%@", [self.db selectAll]);
        // 关闭数据库
        // [self.db closeDB];
    }
    self.flag = !self.flag;
    
}

#pragma mark - 收藏夹的方法
- (void)clickFaviriteButtonAction:(UIButton *)button
{
    ComSaveViewController *comVC = [[ComSaveViewController alloc]init];
    [self presentViewController:comVC animated:YES completion:^{
        
    }];
    [comVC release];

}


- (void)clickSegmentcontrol:(UISegmentedControl *)seg
{
    //self.segmentControl.selectedSegmentIndex
    if (0 == seg.selectedSegmentIndex) {
      self.strCom = @"http://app.api.autohome.com.cn/autov4.6/club/topics-a2-pm2-v4.6.1-b200009-bto-r0-ss0-o0-p1-s50-qf0.html";

    }else if (1 == seg.selectedSegmentIndex){
    self.strCom = @"http://app.api.autohome.com.cn/autov4.6/club/topics-a2-pm2-v4.6.1-b200009-bto-r0-ss0-o2-p1-s50-qf0.html";
     
    }else{
        self.strCom = @"http://app.api.autohome.com.cn/autov4.6/club/topics-a2-pm2-v4.6.1-b200009-bto-r1-ss0-o0-p1-s50-qf0.html";
    }
    
    NSString *ipS = self.foru.bbsid;
    self.str = [self.strCom stringByReplacingOccurrencesOfString:@"200009" withString:ipS];
    [self handerData];
    
}


- (void)handerData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:self.str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        NSMutableArray *listArray = [[result objectForKey:@"result"]objectForKey:@"list"];
        [self.arr removeAllObjects];
        for (NSDictionary *listDic in listArray) {
            Forum *forum = [[Forum alloc]initWithDictionary:listDic];
            [self.arr addObject:forum];
            [forum release];
        }
        self.rowcountStr = [[result objectForKey:@"result"]objectForKey:@"rowcount"];
        self.rowcountL.text = [NSString stringWithFormat:@"共%@帖", self.rowcountStr];
         [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@", error);}];
}


- (void)handerData:(NSString *)string
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
          NSMutableArray *listArray = [[result objectForKey:@"result"]objectForKey:@"list"];
         self.pageIndex =  [[result objectForKey:@"result"] objectForKey:@"pageindex"];
        for (NSDictionary *listDic in listArray) {
            Forum *forum = [[Forum alloc]initWithDictionary:listDic];
            [self.arr addObject:forum];
            [forum release];
            
        }
        self.rowcountStr = [[result objectForKey:@"result"]objectForKey:@"rowcount"];
        self.rowcountL.text = [NSString stringWithFormat:@"共%@帖", self.rowcountStr];
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@", error);}];
}



#pragma mark - 刷新的方法
- (void)addHeader:(UITableView *)header;
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        [self handerData];
        
        NSLog(@"KKk______kk");
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView headerEndRefreshing];
            NSLog(@"KKkkk");
        });
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
}

- (void)addFooter:(UITableView *)footer
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
        
        self.num = [self.pageIndex integerValue];
        self.num += 1;
        NSString *str = [self.str stringByReplacingOccurrencesOfString:@"p1" withString: [NSString stringWithFormat:@"p%ld", self.num]];
        NSLog(@"%ld", self.num);
        NSLog(@"%@ ", str);
        [self handerData:str];

        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView footerEndRefreshing];
            
        });
    }];
}

#pragma mark- tableView 方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *str = @"reuse";
    ComTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[ComTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
    }
    Forum *foru = [self.arr objectAtIndex:indexPath.row];
    cell.foru = foru;
    return cell;
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (self.view.frame.size.height - 110 - 49) / 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelectViewController *selectVC = [[SelectViewController alloc]init];
    Forum *forum = [self.arr objectAtIndex:indexPath.row];
    selectVC.foruF = forum;
    [self presentViewController:selectVC animated:YES completion:^{
    }];
    [selectVC release];
}



#pragma mark - finderButton
- (void)clickFinderButton:(UIButton *)button
{
    FinderViewController *finderVC = [[FinderViewController alloc]init];
    [self presentViewController:finderVC animated:YES completion:^{
    }];
    [finderVC release];
}
#pragma mark - returnButton
- (void)clickReturnButton:(UIButton *)button
{
 [self dismissViewControllerAnimated:YES completion:^{
}];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
